package com.unionftech.common.common.language

import android.annotation.SuppressLint
import android.content.Context
import android.text.TextUtils
import androidx.annotation.StringRes
import com.unionftech.baselibrary.base.BaseApplication
import com.unionftech.common.utils.SpUtils
import org.json.JSONObject

object DynamicResourceManager {
    private val dynamicStrings = mutableMapOf<String, String>()

    @JvmStatic
    fun loadDynamicStrings(languageCode: String) {
        val json = SpUtils.getInstance().getString(languageCode)
        if (!TextUtils.isEmpty(json)) {
            try {
                val jsonObject = JSONObject(json)
                //获取所有的Model的key
                val modelsKey = jsonObject.keys()
                while (modelsKey.hasNext()) {
                    val model = modelsKey.next()
                    //获取对应model的JSON对象
                    val modelObject = jsonObject.optJSONObject(model)
                    //获取所有string对应的key
                    val keys = modelObject?.keys()
                    if (keys != null) {
                        while (keys.hasNext()) {
                            val key = keys.next()
                            //获取string的值
                            val value = modelObject.optString(key)
                            dynamicStrings[key] = value
                        }
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    @JvmStatic
    fun getString(@StringRes id: Int): String {
        return getString(BaseApplication.appContext, id)
    }

    /**
     * 获取字符串，如果国际化中没找到就去strings.xml中找
     */
    @JvmStatic
    fun getString(context: Context, @StringRes id: Int): String {
        return try {
            val key = context.resources.getResourceEntryName(id)
            dynamicStrings[key] ?: context.resources.getString(id)
        } catch (e: Exception) {
            ""
        }
    }

    @JvmStatic
    @SuppressLint("DiscouragedApi")
    fun getString(context: Context, key: String): String {
        val identifier = context.resources.getIdentifier(key, "string", context.packageName)
        return getString(context, identifier)
    }

    @JvmStatic
    @SuppressLint("DiscouragedApi")
    fun getString(key: String): String {
        return getString(BaseApplication.appContext, key)
    }
}